package servlet;

import bean.Menu;
import bean.Role;
import service.MenuService;
import service.RoleService;
import service.impl.MenuServiceImpl;
import service.impl.RoleServiceImpl;
import util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;


@WebServlet(urlPatterns = "/power/role/roles")
public class RoleServlet extends HttpServlet {

    private RoleService roleService = new RoleServiceImpl();
    private MenuService menuService = new MenuServiceImpl();


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String method = req.getParameter("method");

        if ("insert".equals(method)) {
            insert(req, resp);
        }else if ("findbyid".equals(method)){
            findById(req,resp);
        } else if ("update".equals(method)) {
            update(req, resp);
        }else if ("delete".equals(method)){
            delete(req, resp);
        }else if ("selectmenus".equals(method)){
            selectMenus(req, resp);
        }

        else {
            select(req, resp);
        }


    }


    /**
     * 查询角色数据，并分页展示
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void select(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //接收参数（分页参数+模糊查询参数）
        String index = req.getParameter("index");

        int pageIndex = (index == null || index.length() == 0) ? 1 : Integer.parseInt(index);

        //调取service方法（1.查询数据列表方法 2.查询总条数的方法）

        PageUtil pageUtil = new PageUtil();

        //调取service方法

        List<Role> roleList = roleService.getRoleList(pageIndex, pageUtil.getPageSize());
        int total = roleService.total();

        //工具类存储对象数据
        pageUtil.setTotal(total);
        pageUtil.setPageIndex(pageIndex);
        pageUtil.setDataList(roleList);


        //页面存值，并跳转
        req.setAttribute("page", pageUtil);
        req.getRequestDispatcher("list.jsp").forward(req, resp);


    }


    /**
     * 新增角色信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void insert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取页面数据
        String roleId = req.getParameter("roleid");
        String roleName = req.getParameter("roleName");
        String roleState = req.getParameter("roleState");
        //获取复选属性的多个值
        String[] menuIds = req.getParameterValues("menuId");


        //将参数封装到用户对象中
        Role role = new Role();
        role.setRoleName(roleName);
        role.setRoleState(Integer.parseInt(roleState));

        List<Menu> menuList = new ArrayList<>();

        for(String mid:menuIds) {
            Menu menu = new Menu();
            menu.setMenuId(Integer.parseInt(mid));

            menuList.add(menu);

        }

        role.setMenuList(menuList);


        //调取service方法，获取数据入库时的影响行数

        int i = roleService.insert(roleName,Integer.parseInt(roleState),menuIds);

        resp.setContentType("text/html;charset=utf-8");

        PrintWriter writer = resp.getWriter();

        //页面数据更新
        if (i > 0) {
            writer.println("<script>alert('新增成功~');location.href='/power/role/roles'</script>");

        } else {
            writer.println("<script>alert('新增失败!');location.href='/power/role/roles?method=selectmenus'</script>");
        }
    }


    /**
     * 通过角色主键查询用户信息获取全部信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取页面参数
        int roleId = Integer.parseInt(req.getParameter("roleid"));
        
        //根据用户主键查询用户信息

        Role role = roleService.findById(roleId);

        //查询角色菜单列表

        List<Menu> menuList = menuService.getMenuList();

        //角色的菜单
        List<Menu> roleMenus = menuService.getRoleMenu(roleId);


        role.setMenuList(roleMenus);

        //存值
        req.setAttribute("role",role);
        req.setAttribute("menuList",menuList);


        //转发跳转页面
        req.getRequestDispatcher("edit.jsp").forward(req,resp);


    }


    /**
     * 修改角色信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //先获取页面的数据，从页面获取的数据都为String类型
        int roleId = Integer.parseInt(req.getParameter("roleId"));
        String roleName = req.getParameter("roleName");
        String roleState = req.getParameter("roleState");
        String[] menuId = req.getParameterValues("menuId");

        List mennus = new ArrayList();
        for(String s : menuId) {
            mennus.add(s);

        }

        //先存页面数据值
        Role role = new Role();
        role.setRoleId(roleId);
        role.setRoleName(roleName);
        role.setRoleState(Integer.parseInt(roleState));
        role.setMenuIds(mennus);

        //调取service方法，通过修改对象信息修改页面数据
        int i = roleService.update(role);

        int flag = menuService.updateMenu(roleId,menuId);



        //跳转页面，转发数据
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter writer = resp.getWriter();

        //页面数据更新
        if(i>0&&flag>0){
            writer.println("<script>alert('更新成功');location.href='/power/role/roles'</script>");
        }else{
            writer.println("<script>alert('更新失败');location.href='/power/role/roles?method=findbyid?roleId="+roleId+"'</script>");
        }



    }


    /**
     * 通过主键获取角色信息并删除
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取角色主键
        String roleId = req.getParameter("roleid");

        //调用service方法
        int i = roleService.delete(Integer.parseInt(roleId));

        resp.setContentType("text/html;charset=utf-8");

        PrintWriter writer = resp.getWriter();

        if(i>0){
            writer.println("<script>alert('删除成功');location.href='/power/role/roles'</script>");
        }else{
            writer.println("<script>alert('删除失败');location.href='/power/role/roles'</script>");
        }


    }


    /**
     * 查询菜单列表
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void selectMenus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //调取service方法

        List<Menu> menuList = menuService.getMenuList();
        //向前端页面存值
        req.setAttribute("menulist",menuList);

        //转发数据，跳转页面
        req.getRequestDispatcher("add.jsp").forward(req,resp);


    }


}

